import os
import time

from flask import g, Blueprint, redirect, url_for, request, current_app, jsonify
from flask_login import login_user, logout_user

from exts import db, get_time, dict_to_str
from models import Capture, PictureCut, PassersBy, Group

bp = Blueprint("api_capture", __name__, url_prefix="/api/capture")


@bp.route("/group_set_data", methods=['POST'])
def group_set_data():
    mask = int(request.form.get('mask'))
    no_mask = int(request.form.get('no_mask'))

    group = Group(
        mask=mask,
        no_mask=no_mask
    )
    db.session.add(group)
    db.session.commit()

    return "success"


@bp.route("/set_data", methods=['POST'])
def set_data():
    person_id = request.form.get('id')
    person_label = request.form.get('label')

    c = Capture(
        person_id=person_id,
        person_label=person_label
    )
    db.session.add(c)
    db.session.commit()

    return "success"


@bp.route("/save_picture_cut", methods=['POST'])
def save_picture_cut():
    # print(get_time())
    uploaded_file = request.files.get('file')
    suffix = '.' + uploaded_file.filename.split('.')[-1]  # 获取文件后缀名
    filename = uploaded_file.filename.replace(".", "").replace("\\", "").replace("/", "")
    # basedir = os.path.abspath(os.path.dirname(__file__)).replace("blueprints", "")  # 获取当前文件路径
    new_dir = os.path.join("static", "save_picture_cut", filename + str(int(time.time())) + suffix)  # 拼接相对路径
    uploaded_file_path = os.path.join(current_app.root_path, new_dir)  # 拼接图片完整保存路径,时间戳命名文件防止重复
    uploaded_file.save(uploaded_file_path)  # 保存文件
    # size = os.path.getsize(uploaded_file_path)

    pc = PictureCut(
        path="/"+new_dir.replace("\\", "/")
    )

    db.session.add(pc)
    db.session.commit()

    return "success"


@bp.route("get_picture_cut")
def get_picture_cut():
    # id_camera = request.values.get("id_camera")
    video_list = db.session.query(PictureCut).order_by(PictureCut.id.desc()).all()
    return jsonify(list(map(dict_to_str, video_list)))


@bp.route("/get_interactive_data")
def get_interactive_data():
    mask = []
    no_mask = []

    for i in db.session.query(Group).order_by(Group.id.desc()).paginate(page=1, per_page=40).items:
        mask.append(i.mask)
        no_mask.append(i.no_mask)

    data = {
        "series": [
            {
                'name': 'mask',
                'type': 'line',
                'stack': 'Total',
                'areaStyle': {},
                'emphasis': {
                    'focus': 'series'
                },
                'data': mask
            },
            {
                'name': 'no mask',
                'type': 'line',
                'stack': 'Total',
                'areaStyle': {},
                'emphasis': {
                    'focus': 'series'
                },
                'data': no_mask
            },
            {
                'name': 'all',
                'type': 'line',
                'stack': 'Total',
                'areaStyle': {},
                'emphasis': {
                    'focus': 'series'
                },
                'data': list(map(lambda x, y: x + y, mask, no_mask))
            },
        ]
    }

    return jsonify(data)


@bp.route("/get_zhuzhuangtu_data")
def get_zhuzhuangtu_data():
    count_mask = len(db.session.query(PassersBy).filter(PassersBy.person_label == "mask").all())
    count_no_mask = len(db.session.query(PassersBy).filter(PassersBy.person_label == "no_mask").all())
    # for i in db.session.query(Capture).all():
    #     count_mask += int(i.mask)
    #     count_no_mask += int(i.no_mask)
    data = {
        "data": [
            {
                'value': count_mask,
                'itemStyle': {
                    'color': '#12ED93'
                }
            },
            {
                'value': count_no_mask,
                'itemStyle': {
                    'color': '#3F77FE'
                }
            },
            {
                'value': count_no_mask + count_mask,
                'itemStyle': {
                    'color': '#d223e7'
                }
            }
        ]
    }

    return jsonify(data)


@bp.route("/get_meiguitu_data")
def get_meiguitu_data():
    count_mask = len(db.session.query(PassersBy).filter(PassersBy.person_label == "mask").all())
    count_no_mask = len(db.session.query(PassersBy).filter(PassersBy.person_label == "no_mask").all())
    # for i in db.session.query(GroupOfPeople).all():
    #     count_mask += int(i.mask)
    #     count_no_mask += int(i.no_mask)
    # mask = int(1000*count_mask/(count_mask+count_no_mask))
    data = {
        "data": [
            {'value': count_mask, 'name': 'mask'},
            {'value': count_no_mask, 'name': 'no mask'},
            {'value': count_mask + count_no_mask, 'name': 'all'}
        ]
    }

    return jsonify(data)
